package sdk.webview.fmc.com.fmcsdk.manager;

import android.content.Context;
import android.content.Intent;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.smtt.sdk.QbSdk;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.activity.LoginActivity;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.MyTaskNum;
import sdk.webview.fmc.com.fmcsdk.bean.SystemSetting;
import sdk.webview.fmc.com.fmcsdk.bean.User;
import sdk.webview.fmc.com.fmcsdk.service.LocationService;
import sdk.webview.fmc.com.fmcsdk.service.UploadImageService;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.NetworkUtils;
import sdk.webview.fmc.com.fmcsdk.util.PreferencesHelper;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.RetrofitFactory;


/**
 * Created by ydm on 2018/6/29.
 */

public class FMSdk {

    private static String loadUrl;
    private static LoginFMCallBack loginFMCallBack;
    private static GotoMainBack gotoMainBack;
    private static PushCallBack pushCallBack;
    private static Context contexts;
    private static FMSdk instance;
    private String messageId;//消息ID
    private String messageSubtitle;
    private String messageReceipt;
    private String messageType;//消息类型
    private String messageTitle;//消息标题
    private String messageUrl;
    private static Intent gpsIntent;
    private static Intent uploadImageIntent;

    private static final String SUCCESS_STATUS = "200";//请求成功

    //初始化SDK
    public static void init( Context context) {
        contexts = context;
        QbSdk.initX5Environment(context, new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                KLog.e("success");
            }

            @Override
            public void onViewInitFinished(boolean b) {
                if (b) {
                    KLog.e("FMSdk", "X5加载成功" );
                }else {
                    KLog.e("FMSdk", "X5加载失败");
                }
            }
        });
    }


    //开启离线图片上传服务监听
    private static void startService() {
        //定位服务
        SystemSetting systemSetting = PreferencesHelper.getData(SystemSetting.class);
        //设置标题名称
        if (systemSetting != null) {
            SystemSetting.RecordBean record = systemSetting.getRecord();
            if (record!=null) {
                String  is_gps =record.getIS_GPS();
                if (!TextUtils.isEmpty(is_gps)) {
                    //开启员工GPS追踪
                    if (is_gps.equals("1")) {
                        if (!TextUtils.isEmpty(record.getTRAJECTORY_CYCLE())) {
                            gpsIntent = new Intent(contexts, LocationService.class);
                            gpsIntent.putExtra("gpsTime", record.getTRAJECTORY_CYCLE());
                            contexts.startService(gpsIntent);
                        }
//
                    }
                }
            }
        }
        /**启动上传图片的服务，如果有图片则上传*/
        uploadImageIntent = new Intent(contexts, UploadImageService.class);
        contexts.startService(uploadImageIntent);
    }

    /**
     *登录FM系统
     * @param map 参数
     * @return
     */
    public static void call(Map<String,String> map,LoginFMCallBack loginFMCallBacks){
        PreferenceManager.getDefaultSharedPreferences(contexts).edit().putBoolean(Constant.IS_SDK,true).apply();
       loginFMCallBack = loginFMCallBacks;
        String url;
        if (map==null){
            url = "";
        }else {
            url = map.get("url");
        }
        if (TextUtils.isEmpty(url)){
            String baseUrl = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
            if (TextUtils.isEmpty(baseUrl)) {
                //如果URL是空，弹出登录和服务器连接设置界面
                Intent intent = new Intent();
                intent.setClass(contexts, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                contexts.startActivity(intent);
            }else {
                //如果之前有打开过的H5界面，先关闭掉在打开新的
                boolean activityExist = AppManager.isActivityExist(H5Activity.class);
                if (activityExist){
                    AppManager.getAppManager().finishActivity(H5Activity.class);
                }
                String string = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
                startH5(string+"/?accessToken=" +UserHelper.getToken()+"&fromUN=true");
            }
        }else {
            String token = map.get("token");
            PreferenceManager.getDefaultSharedPreferences(contexts).edit().putString(Constant.BASE_ADDRESS_URL,url).apply();
            if (TextUtils.isEmpty(token)) {
                Toast.makeText(contexts,"token不能为空",Toast.LENGTH_SHORT).show();
                return;
            }else {
                getUserInfo(token);

            }

        }

    }


    public static void  onDestroy (){
        stopAllService(contexts);
    }


    /**
     * 获取用户信息
     */
    public static void getUserInfo(final String accessToken) {
        String baseUrl = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
        ApiFactory.getFactory().create(UserApi.class).getUserInfo(baseUrl + Url.GET_USER_INFO,Url.XMLHTTPREQUEST,accessToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<User>() {
                               @Override
                               public void onCompleted() {}

                               @Override
                               public void onError(Throwable e) {
                                   if (loginFMCallBack!=null){
                                       loginFMCallBack.loginStatus(500);
                                   }
//                                   NetworkUtils.exceptionToast(contexts,e);
                               }
                               @Override
                               public void onNext(User baseData) {
                                   //如果成功了发送数据，如果是token过期跳转到登录界面
                                   if (baseData.getStatus().equals(SUCCESS_STATUS)) {
                                       baseData.getRecord().setAccessToken(accessToken);
                                       getSystemSettingInfo(accessToken);
                                       UserHelper.saveUser(baseData);
                                       //设置系统返回的多语言默认值
                                       String defaultLang = baseData.getRecord().getDefaultLang();
                                       if (!TextUtils.isEmpty(defaultLang)) {
                                           XLog.i(defaultLang);
                                           String[] stringArray = contexts.getResources().getStringArray(R.array.multi_language_code);
                                           for (int i = 0; i < stringArray.length; i++) {
                                               if (stringArray[i].equals(defaultLang)) {
                                                   PreferenceManager.getDefaultSharedPreferences(contexts).edit().putInt("lang", i).apply();
                                               }
                                           }
                                       }
                                   } else {
                                       if (loginFMCallBack!=null){
                                           loginFMCallBack.loginStatus(401);
                                       }
                                   }
                               }
                  });
    }


    /**
     * 获取系统设置
     */
    public static void getSystemSettingInfo(final String accessToken) {
        final String baseUrl = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
        ApiFactory.getFactory().create(UserApi.class).getSystemSettingInfo(baseUrl + Url.GET_SYS_SETTING,Url.XMLHTTPREQUEST,accessToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<SystemSetting>() {
                    @Override
                    public void onCompleted() {}

                    @Override
                    public void onError(Throwable e) {
                        if (loginFMCallBack!=null){
                            loginFMCallBack.loginStatus(500);
                        }
                        NetworkUtils.exceptionToast(contexts,e);
                    }
                    @Override
                    public void onNext(SystemSetting baseData) {
                        //如果成功了发送数据，如果是token过期跳转到登录界面
                        if (baseData.getStatus().equals(SUCCESS_STATUS)) {
                            PreferencesHelper.saveData(baseData);
                            if (loginFMCallBack!=null){
                                loginFMCallBack.loginStatus(200);
                            }
                            startService();
                        } else {
                            if (loginFMCallBack!=null){
                                loginFMCallBack.loginStatus(401);
                            }
                        }
                    }
                });
    }


    /**
     * 获取待办任务数量
     */
     public static void   getMessageCount(String token,final TaskCountCallBack taskCountCallBack){
                 String address =  PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL,"");
                 ApiFactory.getFactory().create(UserApi.class).getMyTaskNum(address + "/uc/wf/task/total",token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<MyTaskNum>() {
                    @Override
                    public void onCompleted() {}

                    @Override
                    public void onError(Throwable e) {
                        if (taskCountCallBack!=null) {
                            taskCountCallBack.getMessageCountError(500);
                        }
                        NetworkUtils.exceptionToast(contexts,e);
                    }
                    @Override
                    public void onNext(MyTaskNum baseData) {
                        //如果成功了发送数据，如果是token过期跳转到登录界面
                        if (baseData.getStatus().equals(SUCCESS_STATUS)) {
                            if (taskCountCallBack!=null)
                            taskCountCallBack.getMessageCountSuccess(baseData.getRecord().getTotal());
                        }else {
                            if (taskCountCallBack!=null) {
                                taskCountCallBack.getMessageCountError(401);
                            }
                        }

                    }
                });
    }


    public static void  push(String msg,PushCallBack pushCallBacks){
        pushCallBack = pushCallBacks;
        String token="";
        //msg是推送消息的内容体
        String url = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
        if (!TextUtils.isEmpty(msg)){
            try {
                JSONObject json = new JSONObject(msg);
                //解析msg里面的url
                String msgUrl = json.optString("url");
                 token = json.optString("token");
                if (TextUtils.isEmpty(token)) {
                    Toast.makeText(contexts,"token不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!TextUtils.isEmpty(msgUrl)) {
                    if (!msgUrl.startsWith("http")){
                        loadUrl = url+"/"+msgUrl.replace("#accessToken#",token);
                    }else {
                        loadUrl = msgUrl.replace("#accessToken#",token);
                    }
                }else {
                    //如果有消息体，但是没有URL，默认加载FMC消息列表界面，待定义
                    Toast.makeText(contexts,"没有找到指定的跳转页面",Toast.LENGTH_SHORT).show();
                    return;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else {
            Toast.makeText(contexts,"没有找到指定的msg",Toast.LENGTH_SHORT).show();
            return;
        }
//        UserHelper.getSavedUser().getRecord().setAccessToken(token);
          sendHeartBeat(0,token);


    }

    /**
     * 发送心跳接口
     */
    private static void sendHeartBeat(final int type,final String token) {
         final String baseUrl = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
        ApiFactory.getFactory().create(UserApi.class).sendHeartBeat(baseUrl + Url.SEND_HEARTBEAT,Url.XMLHTTPREQUEST,token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) { }
                    @Override
                    public void onNext(BaseData result) {//成功后向后台发送GPS数据
                        if (result.getStatus().equals(Url.TOKEN_ERROR_STATUS)||result.getStatus().equals(Url.TOKEN_FORBIDDEN)) {
                            XLog.i("推送消息token过期.");
                            if (pushCallBack!=null){
                                pushCallBack.pushStatus(401);
                            }
                            if (gotoMainBack!=null){
                                gotoMainBack.gotoMainStatus(401);
                            }
                        }else if (result.getStatus().equals(Url.SUCCESS_STATUS)){
                            boolean activityExist = AppManager.isActivityExist(H5Activity.class);
                            if (activityExist) {
                                AppManager.getAppManager().finishActivity(H5Activity.class);
                            }
                            if (type==0) {
                                startH5(loadUrl + "&fromUN=true");
                            }else if(type==1){
                                startH5(baseUrl + "/h5/mytask/?accessToken=" + token + "&fromUN=true");
                            }
                        }else {
                            Toast.makeText(contexts,"当前网络连接失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
    /**
     * 关闭服务
     */
    public static void stopAllService(Context context){
        //停止定位和上传图片
        if (gpsIntent != null) {
            Log.i("FmsSdk","关闭定时服务");
            context.stopService(gpsIntent);
        }
        if (uploadImageIntent!=null) {
            context.stopService(uploadImageIntent);
        }
    }

    public static void  startServices(){
        startService();
    }
    //如果是标准版而非SDK方式，做一些对应的处理
    public static void standard(boolean flag,String appName,String versionStr,String address,Context context){
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(Constant.IS_SDK,false).apply();
        PreferenceManager.getDefaultSharedPreferences(context).edit().putString(Constant.APP_NAME,appName).apply();
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(Constant.STANDARD,flag).apply();
        PreferenceManager.getDefaultSharedPreferences(context).edit().putString(Constant.FMC_VERSION_TIME,versionStr).apply();
        if (TextUtils.isEmpty(PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL,""))) {
            PreferenceManager.getDefaultSharedPreferences(context).edit().putString(Constant.BASE_ADDRESS_URL, address).apply();
        }
    }

    /**
     * 消息数量回调
     */
    public interface TaskCountCallBack{
        void getMessageCountSuccess(int count);
        void getMessageCountError(int status);
    }
    /**
     * 登录回调
     */
    public interface LoginFMCallBack{
        void loginStatus(int status);
    }
    /**
     * token过期回调
     */
    public interface PushCallBack{
        void pushStatus(int status);
    }

    /**
     * token过期回调
     */
    public interface GotoMainBack{
        void gotoMainStatus(int status);
    }

    //前外待办列表
    public static void gotoTaskListAct(String token){

        String string = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
        startH5(string+"/h5/mytask/?accessToken=" +token+"#/myTask"+"&fromUN=true");
    }
    //前往首页
    public static void gotoMainAct(String token,GotoMainBack gotoMainBacks){
        gotoMainBack = gotoMainBacks;

        if(NetworkUtils.isAvailable(contexts)){
            sendHeartBeat(1,token);
        }else {
            String string = PreferenceManager.getDefaultSharedPreferences(contexts).getString(Constant.BASE_ADDRESS_URL, "");
            startH5(string + "/h5/mytask/?accessToken=" + token + "&fromUN=true");
        }
    }

    private static void startH5(String url){
        Intent intent = new Intent();
        intent.putExtra(Constant.H5_TITLE, "");
        intent.putExtra(Constant.HIDE_HEADER, false);
        intent.putExtra(Constant.H5_URL, url);//加载的rul
        intent.setClass(contexts, H5Activity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        contexts.startActivity(intent);
    }
}
